package test3.GUI;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Highlighter;
import java.awt.*;
import java.awt.event.*;

/**
 * Created by IntelliJ IDEA.
 * User: Fili
 * Date: Sep 1, 2005
 * Time: 9:16:44 AM
 */
public class UnderlinedTextArea extends JTextPane implements ActionListener, DocumentListener, KeyListener
{
    private static UnderlineHighlighter.UnderlineHighlightPainter underliner = null;

    private Timer timer;


    public UnderlinedTextArea()
    {
        setupStuff();
    }

    public void setupStuff()
    {
        if (underliner == null)
            underliner = new UnderlineHighlighter.UnderlineHighlightPainter(Color.red, 1);

        getDocument().addDocumentListener(this);
        addKeyListener(this);
        timer = new Timer(1000, this);
        timer.setRepeats(false);
        underline();
    }

    public void underline()
    {
        if (!isEditable())
            return;

        Highlighter h = getHighlighter();

        h.removeAllHighlights();

        try
        {
            h.addHighlight(0, 10, underliner);
            h.addHighlight(15, 20, underliner);
        }
        catch (BadLocationException e1)
        {
            e1.printStackTrace();
        }

        repaint();
    }

    public void actionPerformed(ActionEvent e)
    {
        underline();
    }

    public void insertUpdate(DocumentEvent e)
    {
        timer.restart();
    }

    public void removeUpdate(DocumentEvent e)
    {
        timer.restart();
    }

    public void changedUpdate(DocumentEvent e)
    {
    }

    public void keyTyped(KeyEvent e)
    {
    }

    public void keyPressed(KeyEvent e)
    {
        if (!isEditable())
            return;

        if ((e.getKeyChar() == 10) && ((e.getModifiersEx() & InputEvent.CTRL_DOWN_MASK) > 0))
        {
            try
            {
                Rectangle p = modelToView(getCaret().getDot());
                if (p != null)
                {
                    JOptionPane.showMessageDialog(this, "Autocomplete");
                }
            }
            catch (BadLocationException e1)
            {
                e1.printStackTrace();
            }
        }
    }

    public void keyReleased(KeyEvent e)
    {
    }
}
